package org.tote.model;

import java.util.Map.Entry;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MailMessageCreator extends MimeMessageHelper {

	private String mailer_name;
	private static final String ENCODING = "UTF-8";
	private static final Logger LOGGER = LoggerFactory.getLogger(MailMessageCreator.class);

	public MailMessageCreator(MimeMessage mimeMessage, MailMessageTemplate messageTemplate,
			String from) {
		super(mimeMessage, ENCODING);
		mailer_name = from;
		buildMessage(messageTemplate);
	}

	public MailMessageCreator(String from) {
		super(null);
		mailer_name = from;
	}

	private void buildMessage(MailMessageTemplate messageTemplate) {
		assignParameters(messageTemplate);
		try {
			setFrom(mailer_name);
			setSubject(messageTemplate.getSubject());
			setText(messageTemplate.getBody(), true);
		} catch (MessagingException e) {
			LOGGER.error("Unable to build email.");
			throw new RuntimeException("Unable to build email.", e);
		}
	}

	private void assignParameters(MailMessageTemplate messageTemplate) {
		String messageBody = messageTemplate.getBody();
		for (Entry<String, String> parameter : messageTemplate.getParameters().entrySet()) {
			messageBody = messageBody.replaceAll("\\$" + parameter.getKey() + "\\$",
					parameter.getValue());
		}
		messageTemplate.setBody(messageBody);
	}

}
